// src/services/conversion_service.rs - 转换服务

use anyhow::{anyhow, Result as AnyhowResult};
use async_trait::async_trait;
use log::{info, error, debug};
use std::collections::HashMap;
use std::sync::Arc;

use crate::interfaces::DataSourceAdapter;
use crate::models::{DataSourceSchema, OPCUAModel, ValidationResult};
use crate::core::{SemanticConverter, ConversionRequest, ConversionResult};

/// 转换服务
pub struct ConversionService {
    converters: HashMap<String, Arc<dyn SemanticConverter>>,
    adapters: HashMap<String, Arc<dyn DataSourceAdapter>>,
}

impl ConversionService {
    /// 创建新的转换服务
    pub fn new() -> Self {
        Self {
            converters: HashMap::new(),
            adapters: HashMap::new(),
        }
    }

    /// 注册语义转换器
    pub fn register_converter(&mut self, name: String, converter: Arc<dyn SemanticConverter>) {
        self.converters.insert(name, converter);
    }

    /// 注册数据源适配器
    pub fn register_adapter(&mut self, name: String, adapter: Arc<dyn DataSourceAdapter>) {
        self.adapters.insert(name, adapter);
    }

    /// 执行转换
    pub async fn convert(&self, request: ConversionRequest) -> AnyhowResult<ConversionResult> {
        info!("开始执行转换: {:?}", request);

        // 获取适配器
        let adapter = self.adapters.get(&request.data_source_type)
            .ok_or_else(|| anyhow!("未找到数据源适配器: {}", request.data_source_type))?;

        // 连接数据源
        let connection = adapter.connect(&request.data_source_type, &request.connection_string).await?;

        // 提取Schema
        let schema = connection.query_data("SELECT * FROM information_schema.tables").await?;

        // 获取转换器
        let converter = self.converters.get("default")
            .ok_or_else(|| anyhow!("未找到默认转换器"))?;

        // 执行语义转换
        let result = converter.convert(request).await?;

        info!("转换完成");
        Ok(result)
    }

    /// 验证转换结果
    pub async fn validate_result(&self, result: &ConversionResult) -> AnyhowResult<ValidationResult> {
        debug!("验证转换结果");

        // 简单验证逻辑
        let validation_result = ValidationResult {
            is_valid: true,
            errors: vec![],
            warnings: vec![],
        };

        Ok(validation_result)
    }

    /// 获取支持的数据源类型
    pub fn get_supported_data_sources(&self) -> Vec<String> {
        self.adapters.keys().cloned().collect()
    }

    /// 获取支持的转换器类型
    pub fn get_supported_converters(&self) -> Vec<String> {
        self.converters.keys().cloned().collect()
    }
}

impl Default for ConversionService {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
pub trait ConversionServiceTrait: Send + Sync {
    async fn convert(&self, request: ConversionRequest) -> AnyhowResult<ConversionResult>;
    async fn validate_result(&self, result: &ConversionResult) -> AnyhowResult<ValidationResult>;
}

#[async_trait]
impl ConversionServiceTrait for ConversionService {
    async fn convert(&self, request: ConversionRequest) -> AnyhowResult<ConversionResult> {
        self.convert(request).await
    }

    async fn validate_result(&self, result: &ConversionResult) -> AnyhowResult<ValidationResult> {
        self.validate_result(result).await
    }
}